package com.guchenbo.example.compare;

import java.util.*;

/**
 * Comparable 是排序接口，实现该接口表示类可以排序
 * Comparator 是比较接口，实现该接口是定义一个比较器，用来比较两个对象
 * Comparable相当于”内部比较器“，Comparator相当于”外部比较器“
 * <p/>
 * Created by CreGu on 2016/6/12.
 */
public class TestCompare {

    public static void main(String[] args) {
//        System.setProperty("java.util.Arrays.useLegacyMergeSort", "true");

        List<Person> list = new ArrayList<Person>();
        list.add(new Person("jay", 20));
        list.add(new Person("bob", 30));
        list.add(new Person("zero", 25));
        list.add(new Person("lucy", 45));

        System.out.printf("before sort: %s\n", list);
//        sort with comparable
        Collections.sort(list);
        System.out.printf("default sort: %s\n", list);
//      sort with comparator
        Collections.sort(list, new AscAgeComparator());
        System.out.printf("asc age sort: %s\n", list);
//        sort with comparator
        Collections.sort(list, new DescAgeComparator());
        System.out.printf("desc age sort: %s\n", list);

        List<NonComparable> list2 = new ArrayList<>();
        list2.add(new NonComparable("jay"));
        list2.add(new NonComparable("bob"));
        list2.add(new NonComparable("zero"));
        list2.add(new NonComparable("lucy"));
        System.out.printf("before sort: %s\n", list2);
//        sort with comparable
        Collections.sort(list);
        System.out.printf("after sort: %s\n", list2);

        List<String> list3 = new ArrayList<>();
        list3.add("龙井茶");
        list3.add("高速公路");
        list3.add("女装");
        list3.add("家电");
        System.out.printf("before sort: %s\n", list3);
//        sort with comparable
        Collections.sort(list);
        System.out.printf("after sort: %s\n", list3);
    }

    private static class NonComparable {
        private String name;

        public NonComparable(String name) {
            this.name = name;
        }

        @Override
        public String toString() {
            return name;
        }
    }

    private static class Person implements Comparable<Person> {
        private String name;
        private int age;

        public Person(String name, int age) {
            this.name = name;
            this.age = age;
        }

        @Override
        public String toString() {
            return name + "-" + age;
        }

        @Override
        public int compareTo(Person o) {
            return name.compareTo(o.name);
        }
    }


    private static class AscAgeComparator implements Comparator<Person> {
        @Override
        public int compare(Person o1, Person o2) {
            return o1.age-o2.age;
        }
    }

    private static class DescAgeComparator implements Comparator<Person> {

        @Override
        public int compare(Person o1, Person o2) {
//            return o2.age - o1.age;
            return 0;
        }
    }
}
